package com.action;

import com.bean.ResponseBean;
import com.pojo.Dictionary;
import com.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description:
 * @Auther: tz
 * @Date: 2023/11/29 14:31
 */
@CrossOrigin
@RestController
@RequestMapping("/dictionary")
public class DictionaryAction {

    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 获取字典表数据
     * @param type
     * @param code
     * @return
     */
    @RequestMapping("/getDictionaryByTypeCode")
    public ResponseBean getDictionaryByTypeCode(String type, String code){
        Dictionary dictionary = dictionaryService.getDicByCode(type,code);
        if (dictionary == null){
            return ResponseBean.error("字典表没有积分公式");
        }
        return new ResponseBean(200,"查询成功",dictionary);
    }

    /**
     * 设置字典表数据
     * @param type
     * @param code
     * @param value
     * @return
     */
    @RequestMapping("/setDictionaryByTypeCode")
    public ResponseBean setDictionaryByTypeCode(String type, String code, String value){
        Dictionary dictionary = dictionaryService.getDicByCode(type,code);
        if (dictionary == null){
            return ResponseBean.error("字典表没有该数据");
        }
        if (code.equals("birthdays")){
            Pattern pattern2 = Pattern.compile("[0-9]*");
            if (dictionary.getValue() != null){
                Matcher isNum2 = pattern2.matcher(dictionary.getValue());
                if (!isNum2.matches()) {
                    return ResponseBean.error("必须是正整数");
                }
            }
        }
        dictionary.setValue(value);
        if (dictionaryService.updateById(dictionary)){
            return ResponseBean.ok("操作成功");
        }
        return ResponseBean.error("操作失败");
    }

    /**
     * 获取积分公式
     * @return
     */
    @RequestMapping("/getJifenGongshi")
    public ResponseBean getJifenGongshi(){
        Dictionary dictionary = dictionaryService.getDicByCode("user","integralFormula");
        if (dictionary == null){
            return ResponseBean.error("字典表没有积分公式");
        }
        return new ResponseBean(200,"查询成功",dictionary);
    }

    /**
     * 设置积分公式数据
     * @param value
     * @return
     */
    @RequestMapping("/setJifenGongshi")
    public ResponseBean setJifenGongshi(String value){
        Dictionary dictionary = dictionaryService.getDicByCode("user","integralFormula");
        if (dictionary == null){
            return ResponseBean.error("字典表没有积分公式");
        }
        dictionary.setValue(value);
        if (dictionaryService.updateById(dictionary)){
            return ResponseBean.ok("操作成功");
        }
        return ResponseBean.error("操作失败");
    }
}
